//获取应用实例
const app = getApp();
const common = require('./../../../utils/common.js');
const utils = require('./../../../utils/util.js');

import { $wuxSelect, $wuxActionSheet } from 'weapp/index'

Page({
  data: {
    colorList: [],
    is_distribution_price_edit: true,
    template_id: 0,
    detail: null, // 货品详情
    nav_active_id: 6, // 默认第一个的id
    nav_list: [
      { id: 6, name: '计划下单' },
      { id: 4, name: '版单' },
      //  {id: 2, name: '面料情况'},
      // {id: 5, name: '生产计划'},
      // {id: 1, name: 'BOM信息'}, 
    ],
    list_data: [],
    now_page: 0,
    list_total: 0,
    keywords: '',
    table_head: [
      { id: 1, name: '图片', field: 'images', is_checked: false, width: 70 },
      { id: 2, name: '简码', field: 'template_no', is_checked: false, width: 100 },
      { id: 20, name: '性质', field: 'type', is_checked: true, width: 80 },
      { id: 30, name: '完成率', field: 'jindu', is_checked: true, width: 120 },
      { id: 8, name: '需求总量', field: 'total_need_num', is_checked: true, width: 120 },
      { id: 11, name: '未采购总量', field: 'unreceived', is_checked: true, width: 150 },
      { id: 10, name: '已采购总量', field: 'total_caigou_num', is_checked: true, width: 150 },
      { id: 9, name: '无需采购总量', field: 'no_total_need_num', is_checked: true, width: 180 },
      { id: 6, name: '已到齐', field: 'reach_num', is_checked: true, width: 120 },
    ],
    batch_bom_list: [],
    table_scroll_left: 0,
    table_scroll_left_size: 0,
    table_head_size: [
      { id: 1, name: '28\\44\\160\\37\\S', field: 'first', is_checked: true, width: 210 },
      { id: 1, name: '29\\46\\165\\38\\M', field: 'second', is_checked: true, width: 210 },
      { id: 1, name: '30\\48\\170\\39\\L', field: 'third', is_checked: true, width: 210 },
      { id: 1, name: '31\\>50\\175\\40\\XL', field: 'fourth', is_checked: true, width: 230 },
      { id: 1, name: '32\\52\\180\\41\\2XL', field: 'fifth', is_checked: true, width: 230 },
      { id: 1, name: '33\\54\\185\\42\\3XL', field: 'sixth', is_checked: true, width: 230 },
      { id: 1, name: '34\\56\\190\\43\\4XL', field: 'seventh', is_checked: true, width: 230 },
      { id: 1, name: '35\\58\\195\\44\\5XL', field: 'eighth', is_checked: true, width: 230 },
      { id: 1, name: '36\\6XL\\200', field: 'ninth', is_checked: true, width: 180 },
      { id: 1, name: '38\\7XL', field: 'tenth', is_checked: true, width: 130 },
      { id: 1, name: '40', field: 'eleven', is_checked: true, width: 100 },
      { id: 1, name: '42\\均码', field: 'twelve', is_checked: true, width: 135 },
      { id: 1, name: '误差', field: 'diff', is_checked: true, width: 120 },
    ],

    template_bom_list_config: [
      { id: 1, name: '面料名称', field: 'material_name', is_checked: true, width: 210 },
      { id: 1, name: '单件用量', field: 'single_piece', is_checked: true, width: 210 },
      { id: 1, name: '单价', field: 'price', is_checked: true, width: 210 },
      { id: 1, name: '单位', field: 'unit', is_checked: true, width: 210 },
    ],
    template_bom_list: [],

    supplier_list: [],
    supplier_total: 0,
    supplier_now_page: 0,
    supplier_keywords: '',


    show_config: {
      show: false,//显示表单
      show_share: false,//显示操作面板
    },
    material_show_config: {
      show: false,//显示表单
      show_share: false,//显示操作面板
    },
    //计划采购管理配置
    batch_show_config: {
      show: false,//显示表单
    },
    bom_form: {
      material_type: '',
      material_type_index: '',
      bom_name: '',
      price: '',
      single_piece: '',
      bom_detail_id: 0
    },
    material_type_list: [],
    bom_type_list: [
      { id: 1, name: '面料' },
      { id: 2, name: '辅料' },
      { id: 3, name: '通色辅料' }
    ],
    options: [
      { name: '编辑bom', icon: 'https://img.yzcdn.cn/vant/custom-icon-light.png' },
      { name: '删除bom', icon: 'https://img.yzcdn.cn/vant/custom-icon-fire.png' },
    ],
    options2: [
      { name: '编辑面料', icon: 'https://img.yzcdn.cn/vant/custom-icon-light.png' },
      { name: '计划采购管理', icon: 'https://img.yzcdn.cn/vant/custom-icon-light.png' },
    ],
    formData: {
      material_sku_id: '',
      material_id: '',
      purchase_date: '',
      purchase_user: 0,
      supply_id: 0,
      material_name: '',
      material_type: '',
      unit: '',
      price: '',
      cloth_width: '',
      gram_weight: '',
      no_use_rate: '',
      material_attr: '',
      material_grade: '',
      remark: '',
      remark_second: '',
      fileList2: [],
      dead_line: '',
      order_num: '',
    },
    buyer_list: [],
    buyer_list_column: [],
    show_insert_supply_form_config: {
      show: false,
    },
    supply_form: {
      SupplyNa: '',
      SupplyName: ''
    },
    /**生产计划**/
    batchList: [],
    batch_form_config: {//计划弹窗
      show: false,
    },
    batch_supply_form_config: {//计划弹窗的供应商弹窗
      is_show_choose_supplier: false,
      is_shade_screen: false,
    },
    batch_form: {
      id: 0,
      batch_name: '',
      template_cost: '',
      factory_id: 0,
      // SupplyNa: "",
      grade_category: '',
      skus: [],
    },
    batch_form2: {
      goods_purchase_id: 0,
      purchase_type: '',
      supply_id: 0,
      skc: "",
      skus: [],
      purchase_label: ""
    },
    batch_form_config2: {//计划弹窗
      show: false,
    },
    /**生产计划**/

    // 外发工厂
    is_show_half: false,
    is_show_shade: false,
    factory_list: [],
    factory_list_column: [],
    factory_total: 0,
    factory_page: 0,
    factory_keywords: '',
    choose_factory: [],
    TypeOptions: [],
    TypeOptionsCol: [],
    purchase_table_head: [
      { id: 1, name: '件数', field: 'num', is_checked: true, width: 100, show_user: [0] },
      { id: 2, name: '交期', field: 'expectReturnDate', is_checked: true, width: 160, show_user: [0] },
    ],
    // 物料档案 
    // <view class="tr_son">货品颜色</view>
    // <view class="tr_son">面料类型</view>
    // <view class="tr_son">面料名称</view>
    // <view class="tr_son">单件用量</view>
    // <view class="tr_son">单价</view>
    // <view class="tr_son">单位</view> 
    plate_tasts: [],

    // plate_tasts: [
    //    {
    //     "orderCode":"打版需求单号1", // 打版需求单号
    //     "list": [
    //         {
    //             id: 2,
    //             name: '交期',
    //         }
    //     ], 
    //    },
    //    {
    //     "orderCode":"打版需求单号2", // 打版需求单号
    //     "list": [
    //         {
    //             id: 2,
    //             name: '88',
    //         }
    //     ], 
    //    } 
    // ],
    // ***************** 改造 *************
    create_bom_show: false,
    materialColorList: [],// 物料颜色
    // 物料分类
    materialCategoryMeta: [],
    materialCategoryTree: [],
    showMaterialInquiry: false, // 物料选择
    rowData: {}, // 编辑传参数据
    outsourceTypeList: [
      // {
      //   label: "自采-销售",
      //   value: 1,
      // },
      {
        label: "自采-调拨",
        value: "2",
      },
      // {
      //   label: "委外-指定供应商",
      //   value: 3,
      // },
      // {
      //   label: "委外-建议供应商",
      //   value: 4,
      // },
      {
        label: "委外-供应商无限制",
        value: "5",
      },
    ]
  },
 // 物料档案 根据货号获取-打版任务列表，再次获取bom清单
 get_plate_tasts: function (productNo) {
    let that = this;
    let str = '{"needPage":true,"current":1,"size":10,"pages":0,"selectParameter":{"confOrderTypeList":["6102"],"spu":"'+productNo+'","skcName":"","productGoods":"","bomOrderCode":"","sourceNo":"","supplierName":"","designUserName":"","confOrderCategory":null,"componentsTemplateCode":"pdmStandardBom"},"parame":[],"selectParame":[],"orderBy":""}';
    console.log('strstrstrstrstrstr',str);
    // json 转 数组 
    // 发起请求
    common.request_api(
      '/api/pdm/mdBom/pageList',
      JSON.parse(str),
      false
    ).then(res => {
      console.log("res", res)
      // 获取任务编号
      let orderCodes = res.data.records.map(order => order.bomOrderCode);

      var bomOrderCodeToBominfoMap = {}
      res.data.records.forEach((v,k)=>{
        bomOrderCodeToBominfoMap[v.bomOrderCode] = v;
      })

      console.log("bomOrderCodeToBominfoMapbomOrderCodeToBominfoMapbomOrderCodeToBominfoMap", bomOrderCodeToBominfoMap)
      if (orderCodes.length < 1) return true;
      common.request_api(
        '/api/pdm/mdBom/queryBomDetailByBomCodeList',
        orderCodes,
        false
      ).then(res => {
        let plateTasts = [];
        for(var bomOrderCode in res.data){
            let plate = res.data[bomOrderCode]
            let plateBoms = [];
          plate != null && plate.forEach(plateBomItem => {
            console.log('plateBomItem', plateBomItem);
            // 面料  
            plateBomItem.fabricDetailBomVos.forEach(tItem => {
              tItem.bomOrderCode = bomOrderCode
              tItem.orderState = plate.orderState
              tItem.orderStateName = plate.orderStateName
              plateBoms.push(tItem)
            });

            // 辅料 
            plateBomItem.accessoriesDetailBomVos.forEach(tItem => {
              console.log('辅料-tItem', tItem);
              tItem.bomOrderCode = bomOrderCode
              tItem.orderState = plate.orderState
              tItem.orderStateName = plate.orderStateName
              plateBoms.push(tItem)
            });
            // 里料 
            plateBomItem.liningDetailVos.forEach(tItem => {
              console.log('里料-tItem', tItem);
              tItem.bomOrderCode = bomOrderCode
              tItem.orderState = plate.orderState
              tItem.orderStateName = plate.orderStateName
              plateBoms.push(tItem)
            });
            // 公共耗材  
            plateBomItem.commonConsumablesDetailVos.forEach(tItem => {
              console.log('公共耗材-tItem', tItem);
              tItem.bomOrderCode = bomOrderCode
              tItem.orderState = plate.orderState
              tItem.orderStateName = plate.orderStateName
              plateBoms.push(tItem)
            });
            plateTasts.push({
                "orderCode": bomOrderCode,
                "orderState": bomOrderCodeToBominfoMap[bomOrderCode].orderState,
                "orderStateName": bomOrderCodeToBominfoMap[bomOrderCode].orderStateName,
                "list": plateBoms,
              })
          });
         
        }
        // res.data.forEach(plate => {
          
        // });
        that.setData({
          plate_tasts: plateTasts
        })
      });

    });

  },
  // 物料档案 根据货号获取-打版任务列表，再次获取bom清单
  get_plate_tasts222222: function (productNo) {
    let that = this;
    let str = '{"current":1,"size":10,"selectParameter":{"orderLinkCode":"matchBom","componentsTemplateCode":"pdmPrintingTasks","confOrderCategory":"9","orderCode":"","productNo":"' + productNo + '","productGoods":"","confOrderTypeList":[],"designUserIdList":[],"supplierCodeList":[],"merchandiserIdList":[],"versionType":"","customerCodeList":[],"plateDeliveryDateStart":"","plateDeliveryDateEnd":"","productCategoryCodeList":"","isException":"","isTimeout":""}}';
    // json 转 数组 
    // 发起请求
    common.request_api(
      '/api/pdm/pdmPlateTask/queryPlateTaskPage',
      JSON.parse(str),
      false
    ).then(res => {
      console.log("res", res)
      // 获取任务编号
      let orderCodes = res.data.records.map(order => order.orderCode);
      console.log("orderCodes", orderCodes)
      if (orderCodes.length < 1) return true;
      common.request_api(
        '/api/pdm/pdmPlateTask/batchGetPlateTask',
        orderCodes,
        false
      ).then(res => {
        let plateTasts = [];
        res.data.forEach(plate => {
          let plateBoms = [];
          plate.mdBomVo.colorInfs != null && plate.mdBomVo.colorInfs.forEach(plateBomItem => {
            console.log('plateBomItem', plateBomItem);
            // 面料  
            plateBomItem.fabricDetailBomVos.forEach(tItem => {
              tItem.bomOrderCode = plate.mdBomVo.bomOrderCode
              tItem.orderState = plate.mdBomVo.orderState
              tItem.orderStateName = plate.mdBomVo.orderStateName
              plateBoms.push(tItem)
            });

            // 辅料 
            plateBomItem.accessoriesDetailBomVos.forEach(tItem => {
              tItem.bomOrderCode = plate.mdBomVo.bomOrderCode
              tItem.orderState = plate.mdBomVo.orderState
              tItem.orderStateName = plate.mdBomVo.orderStateName
              plateBoms.push(tItem)
            });
            // 里料 
            plateBomItem.liningDetailVos.forEach(tItem => {
              tItem.bomOrderCode = plate.mdBomVo.bomOrderCode
              tItem.orderState = plate.mdBomVo.orderState
              tItem.orderStateName = plate.mdBomVo.orderStateName
              plateBoms.push(tItem)
            });
            // 公共耗材  
            plateBomItem.commonConsumablesDetailVos.forEach(tItem => {
              console.log('公共耗材-tItem', tItem);
              tItem.bomOrderCode = plate.mdBomVo.bomOrderCode
              tItem.orderState = plate.mdBomVo.orderState
              tItem.orderStateName = plate.mdBomVo.orderStateName
              plateBoms.push(tItem)
            });

          });
          plateTasts.push({
            "orderCode": plate.orderCode,
            "orderState": plate.orderState,
            "orderStateName": plate.orderStateName,
            "list": plateBoms,
          })
        });
        that.setData({
          plate_tasts: plateTasts
        })
      });

    });

  },
  handleGetPlateTasts(event){
    console.log(event);
    const detail = event.detail
    this.setData({
      show: false
    })
    if (detail) {
      this.get_plate_tasts(this.data.detail.productNo)
    }
  },
  // 获取物料颜色 
  getMaterialColor() {
    common.request_api(
      "/api/pdm/commonDictionary/queryByGroupIdentification/materialColor",
      {},
      true,
      "get"
    ).then((res) => {
      this.setData({
        materialColorList: res.data,
      });
    });
  },

  // 获取物料分类
  getMaterialCategoryTree() {
    common.request_api(
      "/api/pdm/commonDictionary/queryByGroupIdentification/materialType",
      {},
      true,
      "get"
    ).then((res) => {
      let materialCategoryTree = common.buildTree(res.data);
      let materialCategoryTreeIndexArr = [0, 0];
      let materialCategoryMeta = utils.opAefMetaCateMeta(
        materialCategoryTreeIndexArr,
        materialCategoryTree
      );
      console.log("f1-获取物料分类-materialCategoryMeta",materialCategoryMeta)
      this.setData({
        materialCategoryTree,
        materialCategoryMeta, // 分类列表 
      });
    });
  },
  // 采购时间
  bindPurchaseDateChange: function (e) {
    this.setData({
      [`formData.purchase_date`]: e.detail.value
    })
  },

  bindBatchDateChange: function (e) {
    let index = e.currentTarget.dataset.index
    let field = e.currentTarget.dataset.field
    this.setData({
      [`batch_bom_list[${index}].${field}`]: e.detail.value
    })
  },
  batch_purchase_num_change(e) {
    let { index, field } = e.currentTarget.dataset
    this.setData({
      [`batch_bom_list[${index}].${field}`]: e.detail.value
    })
  },
  // 交期
  bindDeadlineChange: function (e) {
    this.setData({
      [`formData.dead_line`]: e.detail.value
    })
  },
  is_distribution_price_edit() {
    var result = app.request_api('admin/template/is_distribution_price_edit', {}, false);
    result.then(res => {
      this.setData({
        is_distribution_price_edit: res.is_edit
      })
    })
  },
  // 采购员改变时
  buyerChange: function (e) {

    this.setData({
      [`formData.purchase_user`]: this.data.buyer_list[parseInt(e.detail.value)].id,
      [`sel_text.buyer_text`]: this.data.buyer_list[parseInt(e.detail.value)].realname
    })
  },

  chooseDel3: function (e) {
    var index = e.currentTarget.dataset.index;
    this.data.batch_form2.skus.splice(index, 1);
    // 重置data
    this.setData({
      [`batch_form2.skus`]: this.data.batch_form2.skus
    });
  },

  /**
   * 生产计划
   */
  // 搜索工厂
  halfBottomSearch: function (events) {
    var keywords = events.detail.value.trim();
    this.setData({
      factory_keywords: keywords,
      factory_list: [],
      factory_page: 0,
      factory_total: 0
    });
    this.get_factory_list(1);
  },
  // 选择加工厂时
  choose_factory: function (events) {
    var index = events.currentTarget.dataset.index;
    var id = this.data.factory_list[index].id
    var SupplyNa = this.data.factory_list[index].SupplyNa
    let choose_factory = []
    choose_factory.push(SupplyNa);
    console.log('id', id)
    this.setData({
      choose_factory: choose_factory,
      [`batch_form.factory_id`]: id,
      [`batch_form2.supply_id`]: id,
      is_show_shade: false,
      is_show_half: false
    })
  },

  // 删除选择项
  DeleteChoose: function (events) {
    var index = events.currentTarget.dataset.index;

    this.data.choose_factory.splice(index, 1);
    console.log(index, this.data.choose_factory)
    this.setData({
      choose_factory: this.data.choose_factory,
      [`batch_form.factory_id`]: 0
    });
  },

  // 关闭半屏
  close_half: function (e) {
    this.setData({
      is_show_shade: false,
      is_show_half: false
    })
  },

  // 打开半屏
  open_half: function (e) {
    this.setData({
      is_show_shade: true,
      is_show_half: true
    })
  },
  // 获取外发工厂
  get_factory_list: function (is_search = 0) {
    var __this = this;
    // 验证
    if ((this.data.factory_list.length >= this.data.factory_total) && this.data.factory_page > 0) {
      return false;
    }
    // 发起请求
    var result = app.request_api('admin/Factory/index', {
      page: __this.data.factory_page + 1,
      quick_search: __this.data.factory_keywords,
      limit: 100,
    }, false);
    result.then(res => {
      console.log(res)
      if (is_search == 1) {
        __this.setData({
          factory_list: [],
          factory_page: 0,
          factory_total: 0
        })
      }
      let factory_list_column = {};
      res.list.forEach((v, k) => {
        factory_list_column[v.id] = v;
      })
      // console.log ('factory_list_column', factory_list_column)
      __this.setData({
        factory_list: __this.data.factory_list.concat(res.list),
        factory_list_column,
        factory_page: this.data.factory_page + 1,
        factory_total: res.total
      })
    });
  },
  // 选择颜色
  // 当输入生产数量时
  selInputChange: function (e) {
    var index = e.currentTarget.dataset.index;
    var field = e.currentTarget.dataset.field;
    this.data.batch_form.skus[index][field] = e.detail.value;
    this.setData({
      [`batch_form.skus`]: this.data.batch_form.skus
    })
  },

  selInputChange2: function (e) {
    var index = e.currentTarget.dataset.index;
    var field = e.currentTarget.dataset.field;
    this.data.batch_form2.skus[index][field] = e.detail.value;
    this.setData({
      [`batch_form2.skus`]: this.data.batch_form2.skus
    })
  },
  // 外面的货期
  bindGoodsDateChange: function (e) {
    // let index = e.currentTarget.dataset.index
    // var bianl = `batch_form.skus[${index}].expectReturnDate`;
    // this.setData ({
    //     [bianl]: e.detail.value
    // })

    var index = e.currentTarget.dataset.index;
    var field = e.currentTarget.dataset.field;
    this.data.batch_form2.skus[index][field] = e.detail.value;
    this.setData({
      [`batch_form2.skus`]: this.data.batch_form2.skus
    })
  },

  batch_info_input: function (e) {
    let { field, index } = e.currentTarget.dataset
    let { value } = e.detail;
    this.setData({
      [`batch_form.${field}`]: value,
    })
  },
  // 取消选择
  chooseDel: function (e) {
    var index = e.currentTarget.dataset.index;
    this.data.batch_form.skus.splice(index, 1);
    // 重置data
    this.setData({
      [`batch_form.skus`]: this.data.batch_form.skus
    });
  },

  ChooseColor: function (events) {
    var __this = this;
    // 打开选择颜色页面
    wx.navigateTo({
      url: '/pages/choose_color/choose_color?template_id=' + __this.data.template_id,
      events: {
        // 当选择完成时
        changeData: function (data) {
          console.log('选择完成', data);

          __this.setData({
            [`batch_form.skus`]: data,
          });

          const filteredData = data.filter(item => !item.hasOwnProperty('batch_color_id'));

          var names = filteredData.map((v) => v.name);
          __this.getTemplateColorPrices(__this.data.template_id, names);
        }
      },
      success: function (res) {
        // 向被打开页面传送数据
        res.eventChannel.emit('acceptDataFromOpenerPage', {
          sel_list: __this.data.batch_form.skus,
          template_id: __this.data.template_id
        });
      }
    });
  },
  ChooseColor2: function (events) {
    var __this = this;
    // 打开选择颜色页面
    wx.navigateTo({
      url: '/alpha/pages/alpha_choose_color/choose_color?template_id=' + __this.data.template_id,
      events: {
        // 当选择完成时
        changeData: function (data) {
          console.log('选择完成', data);
          //
          __this.setData({
            [`batch_form2.skus`]: data
          });
          //
          // const filteredData = data.filter (item => !item.hasOwnProperty ('batch_color_id'));
          //
          // var names = filteredData.map ((v) => v.name);
          // __this.getTemplateColorPrices (__this.data.template_id, names);
        }
      },
      success: function (res) {
        // 向被打开页面传送数据
        res.eventChannel.emit('acceptDataFromOpenerPage', {
          sel_list: __this.data.batch_form2.skus,
          purchase_table_head: __this.data.purchase_table_head,
          template_id: __this.data.template_id,
          sel_color_list: __this.data.colorList
        });
      }
    });
  },

  getTemplateColorPrices(template_id, colors) {
    var result = app.request_api('admin/template/getTemplateColorInfo', {
      template_id,
      colors: colors
    }, false, 'post');
    result.then(res => {
      console.log(' batch_form.skus', this.data.batch_form.skus, res)
      this.data.batch_form.skus.forEach((v, k) => {
        if (res[v.name] !== undefined) {
          v.goods_id = res[v.name].goods_id
          v.distribution_price = res[v.name].distribution_price
          v.sale_price = res[v.name].sale_price
        }
      })

      this.setData({
        batch_form: this.data.batch_form
      })
    });
  },

  showForm2(e) {
    let index = e.currentTarget.dataset.index
    let id = e.currentTarget.dataset.id
    let choose_factory = []
    let batch_form2 = {}
    console.log('goods_purchase_id', id);
    if (id !== undefined || index !== undefined) {
      let data = this.data.batchList2[index];
      for (var k in this.data.batch_form2) {
        batch_form2[k] = data[k];
      }

      let skus = []
      data.skus.forEach((v) => {
        skus.push({ ...v, name: v.name, plan_total_num: v.plan_total_num })
      })
      console.log('skusskusskusskusskusskus', skus)
      batch_form2.skus = skus
      if (data.SupplyNa != '' && data.SupplyNa !== undefined && data.SupplyNa !== null) {
        choose_factory.push(data.SupplyNa)
      }

    } else {
      batch_form2.goods_purchase_id = 0
      batch_form2.purchase_type = ''
      batch_form2.supply_id = 0
      batch_form2.skus = []
    }
    console.log('batch_form2batch_form2batch_form2batch_form2batch_form2', batch_form2)
    this.setData({
      choose_factory,
      [`batch_form2`]: batch_form2
    });
    this.get_factory_list();
    this.get_type_options();
    this.setData({
      [`batch_form_config.show`]: true,
    });
  },
  showForm(e) {
    let index = e.currentTarget.dataset.index
    let id = e.currentTarget.dataset.id
    let choose_factory = []
    let batch_form = {}
    let batch_form2 = {}
    if (id !== undefined || index !== undefined) {
      let data = this.data.batchList[index];
      for (var k in this.data.batch_form) {
        batch_form[k] = data[k];
      }

      let skus = []
      data.skus.forEach((v) => {
        skus.push({ ...v, name: v.color, num: v.quantity })
      })
      batch_form.skus = skus
      if (data.SupplyNa != '' && data.SupplyNa !== undefined && data.SupplyNa !== null) {
        choose_factory.push(data.SupplyNa)
      }

    } else {
      batch_form.id = 0
      batch_form.batch_name = ''
      batch_form.factory_id = 0
      batch_form.grade_category = ''
      batch_form.template_cost = ''
      batch_form.skus = []


      batch_form2.goods_purchase_id = 0
      batch_form2.purchase_type = ''
      batch_form2.supply_id = 0
      batch_form2.skus = []
    }
    this.setData({
      choose_factory,
      [`batch_form`]: batch_form,
      [`batch_form2`]: batch_form2

    });
    this.get_factory_list();
    this.get_type_options();
    this.setData({
      [`batch_form_config.show`]: true,
    });
  },
  hideForm() {
    this.setData({
      [`batch_form_config.show`]: false,
    });
  },

  TypeOptionsChange(e) {
    let index = e.detail.value
    let value = this.data.TypeOptions[index].label
    this.setData({
      [`batch_form.batch_name`]: value
    })
  },
  /*new*/
  TypeOptionsChange2(e) {
    let index = e.detail.value
    let label = this.data.TypeOptions[index].label
    let value = this.data.TypeOptions[index].value
    console.log(this.data.TypeOptionsCol, value, this.data.TypeOptions[index])
    this.setData({
      [`batch_form2.purchase_type`]: value,
      [`batch_form2.purchase_label`]: label
    })
  },
  /*new*/
  get_type_options() {
    var result = common.request_api('/api/erp/baseDictionary/queryCommonDictionaryAndChild/confOrderCategory?code=1003', {}, false, 'GET');
    result.then(res => {
      let data = res.data
      let data2 = []
      data.forEach((item) => {
        data2[item.value] = item.label
      })

      this.setData({
        TypeOptions: data,
        TypeOptionsCol: data2,
      })
    });
  },
  getBatchList() {
    var result = app.request_api('admin/ProductBatch/getBatchIndex', {
      template_id: this.data.template_id
    }, false);
    result.then(res => {
      this.setData({
        batchList: res,
      });
    });
  },
  getBatchList2() {
    var result = app.request_api('admin/ProductBatchOrder/getPurchseOrderIndex', {
      template_id: this.data.template_id
    }, false);
    result.then(res => {
      this.setData({
        batchList2: res.list,
      });
    });
  },
  // 商品提报
  saveBatch2() {
    const detail = this.data.detail
    let formData = {}
    formData.template_id = this.data.template_id;
    formData.saleOrderType = '1003'
    formData.emergeWay = '3'
    formData.codeRatioCalculation = '1'
    formData.isSubmit = true
    formData.submit = true
    formData.confOrderCategory = '1003'
    formData.relateType = '2'
    formData.confOrderType = this.data.batch_form2.purchase_type
    let skus = [];
    let old_skus = this.data.batch_form2.skus
    this.data.batch_form2.skus.forEach((v, k) => {
      v.delete = false
      v.lineNum = "SA000" + (k + 1)
      v.customerSkc = v.name
      v.skuName = v.name
      v.spu = detail.productNo
      v.productGoods = detail.productGoods
      v.qty = v.num
      v.firstQty = v.num
      let dtos = {}
      dtos.firstQty = v.num
      dtos.skc = v.skc
      dtos.enable = 1
      dtos.skcName = v.name
      dtos.skuName = v.name + ",所有规格"
      dtos.productGoods = detail.productGoods
      v.sizeDetailDtos = []
      v.sizeDetailDtos.push(dtos)
      skus.push(v)
    })
    this.data.batch_form2.erpSaleOrderDetailDtoList = skus
    formData.erpSaleOrderDetailDtoList = skus
    console.log('formDataformDataformDataformDataformData', formData)
    var result = common.request_api('/api/erp/erpSaleOrder/createSaleOrder', formData, true, 'POST', {}, true);
    result.then(res => {
      this.hideForm();
      this.get_purchase_list();
      return;
    }).catch(() => {
      this.data.batch_form2.skus = old_skus
    })
  },
  /**生产计划 */
  /**bom */
  show_insert_supply_form() {
    this.setData({
      [`show_insert_supply_form_config.show`]: true
    })
  },
  saveBatch() {
    this.data.batch_form.template_id = this.data.template_id;
    let skus = [];
    let old_skus = this.data.batch_form.skus
    this.data.batch_form.skus.forEach((v, k) => {
      skus.push({
        color: v.name,
        quantity: v.num,
        delivery_time: v.delivery_time,
        purchase_price: v.purchase_price,
        sale_price: v.sale_price,
        distribution_price: v.distribution_price,
      })
    })
    this.data.batch_form.skus = skus
    if (this.data.batch_form.id != 0 && this.data.batch_form.id !== undefined) {
      var result = app.request_api('admin/ProductBatch/editBatch', this.data.batch_form, true, 'POST', {}, true);
    } else {
      var result = app.request_api('admin/ProductBatch/addBatch', this.data.batch_form, true, 'POST', {}, true);
    }
    //
    result.then(res => {
      this.hideForm();
      this.getBatchList();
      return;
    }).catch(() => {
      this.data.batch_form.skus = old_skus
    })
  },
  delBatch(e) {
    let index = e.currentTarget.dataset.index
    let batchList = this.data.batchList
    let _this = this;
    // 确认提示
    wx.showModal({
      title: '提示',
      content: '您确定要删除计划吗',
      success(res) {
        if (res.confirm) {
          var result = app.request_api('admin/ProductBatch/removeBatch', { id: batchList[index].id }, true, 'POST', {}, true);
          result.then(res => {
            batchList.splice(index, 1)
            _this.setData({
              batchList
            })
            wx.showModal({
              title: '提示',
              content: res.msg,
              showCancel: false,
              complete() {

              }
            });
            this.getBatchList();
          })
        }
      },
    });

  },
  // 打开选择
  open_supplier_choose: function () {
    this.setData({
      is_shade_screen: true,
      is_show_choose_supplier: true
    })
  },
  // 选择供应商
  choose_supplier: function (e) {
    // 验证是否选择的是否和之前一样
    this.setData({
      [`formData.supply_id`]: this.data.supplier_list[parseInt(e.currentTarget.dataset.index)].id,
      [`sel_text.supply_text`]: this.data.supplier_list[parseInt(e.currentTarget.dataset.index)].SupplyNa
    });
    this.close_supplier_choose();
  },
  // 关闭
  close_supplier_choose: function (e) {
    this.setData({
      is_shade_screen: false,
      is_show_choose_supplier: false,
      is_show_choose_pro: false,
    })
  },
  // 获取采购员
  get_buyer_list: function () {
    // 发起请求
    var result = app.request_api('admin/auth.admin/index', {
      select: true,
      limit: 9999,
      group_id: 7
    }, false);
    result.then(res => {
      let buyer_list_column = {};
      res.list.forEach((v, k) => {
        buyer_list_column[v.id] = v;
      })
      this.setData({
        buyer_list_column,
        buyer_list: res.list
      });
    });
    // 返回
    return result;
  },
  material_info_input: function (e) {
    let { field, index } = e.currentTarget.dataset
    let { value } = e.detail;
    this.setData({
      [`formData.${field}`]: value,
    })
  },
  newsupply_info_input: function (e) {
    let { field, index } = e.currentTarget.dataset
    let { value } = e.detail;
    this.setData({
      [`supply_form.${field}`]: value,
    })
  },
  closeSupply() {
    this.setData({
      [`show_insert_supply_form_config.show`]: false,
    })
  },
  insertSupply() {
    if (this.data.supply_form.SupplyNa == '' || this.data.supply_form.SupplyName == '') {
      wx.showModal({
        title: '提示',
        content: '请填写完整',
        showCancel: false,
        complete() {

        }
      });
      return;
    }
    var result = app.request_api('admin/supply/add', {
      SupplyNa: this.data.supply_form.SupplyNa,
      SupplyName: this.data.supply_form.SupplyName
    }, true, 'post', {}, true);
    result.then(res => {
      wx.showModal({
        title: '提示',
        content: res.msg,
        showCancel: false,
        complete() {

        }
      });
      this.setData({
        ['supplier_now_page']: 0,
        [`show_insert_supply_form_config.show`]: false,
      })
      this.get_supplier_list(1);
    })
  },
  // 搜索供应商时
  searchSupplierChange: function (events) {
    var keywords = events.detail.value.trim();

    this.setData({
      [`formData.supply_id`]: keywords,
      [`sel_text.supply_text`]: keywords,
      supplier_keywords: keywords,
      supplier_list: [],
      supplier_now_page: 0,
      supplier_total: 0,
    });
    this.get_supplier_list(1);
  },
  onShareSelect2(e) {
    let index = e.detail.index;
    if (index == 0) {
      if (this.data.formData.material_sku_id == 0) {
        wx.showModal({
          title: '提示',
          content: '没找到面料',
          showCancel: false,
          complete() {

          }
        });
        return;
      }
      this.get_buyer_list()
      this.get_supplier_list()
      this.get_MaterialCategory_list();
      var result = app.request_api('admin/material/sku_get', { material_sku_id: this.data.formData.material_sku_id }, true, 'get', {}, true);
      result.then(res => {
        this.onShareClose2()
        console.log('res', res)
        let form_data = [];
        let formData = this.data.formData
        for (var k in this.data.formData) {
          if (res.data[k] !== undefined) {
            formData[k] = res.data[k]
          } else {
            formData[k] = ''
          }
        }


        this.setData({
          formData,
          [`sel_text.supply_text`]: res.data.SupplyNa
        })
        this.onClickShow2()
      })
    }

    if (index == 1) {
      this.setData({
        ['material_show_config.show_share']: false,
        ['batch_show_config.show']: true
      })
      var result = app.request_api('admin/TemplateBomColor/getBomBatchList', { template_bom_color_id: this.data.formData.template_bom_color_id }, true, 'post', {}, true);
      result.then(res => {
        this.setData({
          batch_bom_list: res.data
        })
      })
    }

  },
  batch_bom_edit(e) {
    let index = e.currentTarget.dataset.index
    this.setData({
      [`batch_bom_list[${index}].editing`]: !this.data.batch_bom_list[index].editing,
    })
  },
  batch_bom_save(e) {
    let index = e.currentTarget.dataset.index
    var result = app.request_api('admin/TemplateBomColor/setBomBatchInfo', this.data.batch_bom_list[index], false, 'POST', {}, true);
    result.then(res => {
      console.log(res)
      if (res.code == 1) {
        wx.showToast({
          title: res.msg,
          icon: 'success',
          duration: 2000
        });
      }
    })
    console.log('batch_bom_list[index]',)
  },
  close_batch_form() {
    this.setData({
      ['batch_show_config.show']: false
    })
  },
  onClickShareShow2: function (e) {
    let { index } = e.currentTarget.dataset
    console.log(this.data.template_bom_list[index])
    let material_sku_id = this.data.template_bom_list[index].material_sku_id
    let template_bom_color_id = this.data.template_bom_list[index].id
    this.setData({
      ['formData.material_sku_id']: material_sku_id,
      ['formData.template_bom_color_id']: template_bom_color_id,
      ['material_show_config.show_share']: true
    })
  },
  onClickShow2: function (e) {
    this.setData({
      ['material_show_config.show']: true
    })
  },
  onClickHide2: function (e) {
    this.setData({
      ['material_show_config.show']: false
    })
  },
  get_purchase_list: function (is_search = 0) {
    var __this = this;

    let selectParameter = { "sort": "11", "spu": __this.data.detail.productNo}

    // 组装条件
    let req_data = {
      current: this.data.now_page + 1,
      needPage: true,
      size: __this.data.limit,
      orderBy: "",
      parame: [],
      selectParameter: selectParameter,
      // "params[status]": __this.data.nav_list[__this.data.active_nav_index].value,
    };

    // 发起请求
    var result = common.request_api('/api/erp/erpSaleOrder/saleSkcPage', req_data, false);
    result.then(res => {
      __this.setData({
        batchList2: res.data.records
      })
    });
    // 返回
    return result;
  },
  // 获取供应商
  get_supplier_list: function (is_search = 0) {
    var __this = this;
    // 验证
    if ((this.data.supplier_list.length >= this.data.supplier_total) && this.data.supplier_now_page > 0) {
      console.log('终止', (this.data.supplier_list.length >= this.data.supplier_total), this.data.supplier_now_page)
      return false;
    }
    // 发起请求
    var result = app.request_api('admin/Supply/index', {
      page: __this.data.supplier_now_page + 1,
      quick_search: __this.data.supplier_keywords,
      limit: __this.data.limit,
      select: true,
    }, false);
    result.then(res => {
      if (is_search == 1) {
        __this.setData({
          supplier_list: [],
          supplier_now_page: 0,
          supplier_total: 0
        })
      }
      __this.setData({
        supplier_list: __this.data.supplier_list.concat(res.list),
        supplier_now_page: this.data.supplier_now_page + 1,
        supplier_total: res.total
      })
    });
    // 返回
    return result;
  },
  onShareClose2: function (e) {
    this.setData({
      ['material_show_config.show_share']: false
    })
  },

  // 录入新物料
  template_purchase: (e) => {
    let { product_no } = e.currentTarget.dataset;
    console.log("录入新物料-product_no", product_no)
    wx.navigateTo({
    //   url: '/alpha/pages/alpha_template_detail/create_material/index?productNo=' + product_no, // +this.data.detail.productNo
      url: '/alpha/pages/alpha_material_form/index'
    });
  },


  create_bom: function (e) {
    let { product_no } = e.currentTarget.dataset;
    console.log("create_bom", product_no)
    this.setData({
      create_bom_show: true
    })
    console.log("create_bom_show", this.data.create_bom_show)
  },

  onClickShow: function (e) {
    this.setData({
      ['show_config.show']: true
    })
  },
  // 获取面料类型
  get_MaterialCategory_list: function () {
    // 发起请求
    var result = app.request_api('admin/MaterialCategory/index', {
      select: true,
      limit: 9999,
      group_id: 7
    }, false);
    result.then(res => {
      var newlist = [];
      res.list.forEach(function (v, k) {
        newlist[v.id] = v;
      })
      this.setData({
        material_type_list: res.list,
        material_type_list_new: newlist
      });
    });
    // 返回
    return result;
  },
  onClickShareShow: function (e) {
    let { index } = e.currentTarget.dataset
    console.log('aa')
    let index2 = this.data.bom_type_list.findIndex(res => res.name == this.data.detail.bom_list[index].material_type)
    this.data.detail.bom_list[index].material_type_index = index2
    this.setData({
      'bom_form': this.data.detail.bom_list[index],
    })
    this.setData({
      ['show_config.show_share']: true
    })
  },
  onClickHide: function (e) {
    this.setData({
      ['show_config.show']: false
    })
  },
  onShareClose: function (e) {
    this.setData({
      ['show_config.show_share']: false
    })
  },
  bom_input_change: function (e) {
    let { field } = e.currentTarget.dataset
    let { value } = e.detail
    if (field == 'price' || field == 'single_piece') {
      const regex = /^[0-9]*(\.[0-9]*)?$/;
      value = value.replace(/[^0-9.]/g, '');
    }
    this.setData({
      [`bom_form.${field}`]: value
    })
    console.log(this.data.bom_form)
  },
  // 获取上传标识
  get_web_config: function () {
    console.log("获取上传标识", this.data.bom_form)
    // 发起请求
    var result = app.request_api('admin/index/index', {}, true, 'GET');
    result.then(res => {
      this.setData({
        web_data: res
      });
    });

  },
  saveMaterial: function (e) {
    var __this = this
    var req_arr = []
    let formData = this.data.formData
    var substring = 'babiboy';
    if (formData.fileList2 !== undefined) {
      var fileList2 = formData.fileList2
      fileList2.forEach(function (v, k) {
        if (v.tempFilePath !== undefined && !v.tempFilePath.includes(substring)) {
          var result = app.request_upload('', {
            cdn_url: __this.data.web_data.siteConfig.apiUrl,
            token: __this.data.web_data.siteConfig.upload.token,
            is_old_file: 0
          }, v.tempFilePath, k, false);
          req_arr.push(result);
          // 处理结果
          result.then(res => {
            let insert_data = {
              "url": res.file_path,
              "thumb": res.file_path,
              "fileType": "image",
              "value": res.file_key
            }
            console.log('insert_data', insert_data)
            formData.fileList2[res.for_i] = insert_data;
            __this.setData({
              formData,
            });
          });
        }
        if (v.thumb !== undefined && !v.thumb.includes(substring)) {
          var result = app.request_upload('', {
            cdn_url: __this.data.web_data.siteConfig.apiUrl,
            token: __this.data.web_data.siteConfig.upload.token,
            is_old_file: 0
          }, v.thumb, k, false);
          req_arr.push(result);
          // 处理结果
          result.then(res => {
            let insert_data = {
              "url": res.file_path,
              "thumb": res.file_path,
              "fileType": "image",
              "value": res.file_key
            }
            formData.fileList2[res.for_i] = insert_data;
            __this.setData({
              formData,
            });
          });
        }
      })
    }
    console.log('提交', this.data.formData)
    Promise.all(req_arr).then(res => {
      var result = app.request_api('admin/Material/mini_save_material', this.data.formData, true, 'POST', {}, true);
      result.then(res => {
        wx.showToast({
          title: res.msg,
          icon: 'success',
          duration: 2000
        });
        this.onClickHide2()
      })
    })

  },
  saveBom: function (e) {
    let data = {
      material_type: this.data.bom_form.material_type,
      template_id: this.data.template_id,
      bom_detail_id: this.data.bom_form.bom_detail_id,
      bom_name: this.data.bom_form.bom_name,
      price: this.data.bom_form.price,
      single_piece: this.data.bom_form.single_piece,
    };
    var result = app.request_api('admin/Template/mini_save_bom', data, true, 'POST', {}, true);
    result.then(res => {
      wx.showToast({
        title: res.msg,
        icon: 'success',
        duration: 2000,
      });
      this.onClickHide();
      this.get_template_detail()
    })
  },
  materialTypeChange2(e) {
    let index = e.detail.value
    this.setData({
      [`formData.material_type`]: this.data.material_type_list[index].id,
      [`formData.material_type_index`]: index
    })
  },
  deleteImage(e) {
    // wx.showToast({
    //     title:'点击了删除',
    //     icon: 'success',
    //     duration: 2000,
    // });
    let index2 = e.detail.index
    let formData = this.data.formData
    formData.fileList2.splice(index2, 1);
    this.setData({
      formData
    })
  },
  afterRead2(event) {
    var __this = this;
    const { file } = event.detail;
    const fileList = this.data.formData.fileList2 || [];
    fileList.push({ ...file });
    var setname = `formData.fileList2`;
    this.setData({ [setname]: fileList });
  },
  materialTypeChange(e) {
    let index = e.detail.value
    this.setData({
      [`bom_form.material_type`]: this.data.bom_type_list[index].name,
      [`bom_form.material_type_index`]: index
    })
  },
  onShareSelect(e) {
    let index = e.detail.index;
    if (index == 0) {
      this.onClickShow()
    } else if (index == 1) {
      this.mini_del_bom()
    }
    this.onShareClose()
  },
  mini_del_bom() {
    let data = {
      template_id: this.data.template_id,
      bom_detail_id: this.data.bom_form.bom_detail_id,
    };
    var result = app.request_api('admin/Template/mini_del_bom', data, true, 'POST', {}, true);
    result.then(res => {
      // wx.showToast({
      //     title: res.msg,
      //     icon: 'success',
      //     duration: 2000,
      // });
      this.onClickHide();
      this.get_template_detail()
    })
  },

  getTemplateBom() {
    var template_id = this.data.template_id
    var result = app.request_api('admin/TemplateBomColor/getTemplateColor', {
      template_id,
    }, false);
    result.then(res => {
      let new_list = {};
      res.forEach((v, k) => {
        new_list[v.id] = v;
      })
      this.setData({
        template_bom_list: res,
        template_bom_list_column: new_list
      })
    })
  },
  /**bom */
  onLoad: function (options) {
    // 设置标题
    wx.setNavigationBarTitle({
      title: '款式详情'
    });
    console.log(options.template_id)
    // 设置模板
    if (options.template_id != undefined) {
      this.setData({
        template_id: options.template_id
      });
      // 获取aef物料相关
      this.getMaterialCategoryTree()
      this.getMaterialColor()
      // 获取模板详情
      this.get_template_detail();
      this.getTemplateBom();
      this.getBatchList();
      this.getBatchList2();
      this.is_distribution_price_edit();
    }
    this.get_web_config();
  },

  // 表格滑动结束
  tr_boxs_scroll_end: function (e) {
    var __this = this;
    setTimeout(function () {
      __this.setData({
        table_scroll_left: e.detail.scrollLeft
      });
    }, 180);
  },

  // 尺寸表格滑动结束
  tr_boxs_scroll_end2: function (e) {
    var __this = this;
    setTimeout(function () {
      __this.setData({
        table_scroll_left_size: e.detail.scrollLeft
      });
    }, 180);
  },

  // 获取详情
  get_template_detail: function () {
    console.log('获取详情-get_template_detail')
    var result = common.request_api('/api/bamboo/PdPublish/getPdSpuDetailById/' + this.data.template_id + '/false', {}, true, 'GET');
    result.then(res => {
      console.log(res);
      res.data.thickness = ''
      res.data.template_type = ''
      res.data.age_name = ''
      res.data.attributeValueList.forEach(function (item, index) {
        if (item.attributeName == '厚度指数') {
          res.data.thickness = item.attributeValueIdsValue
        }
        if (item.attributeName == '版型') {
          res.data.template_type = item.attributeValueIdsValue
        }
        if (item.attributeName == '适龄段') {
          res.data.age_name = item.attributeValueIdsValue
        }
      })
      let arr = [];
      res.data.specAttributeInfoList.forEach(function (item, index) {
        if (item.specAttributeCategoryName == '颜色') {
          item.specAttributeValueList.forEach(function (item1, index1) {
            arr.push(({ ...item1, is_checked: 0 }))
          })
        }
      })
      this.setData({
        detail: res.data,
        colorList: arr
      });
      this.get_purchase_list()
      // 获取面料情况
      this.get_plate_tasts(res.data.productNo) // 打版任务列表，再次获取bom清单

    });
  },

  // 获取BOM信息
  get_list_data: function (is_search = 0) {
    // 验证
    if ((this.data.list_data.length >= this.data.list_total) && this.data.now_page > 0) {
      return false;
    }
    // 组装参数
    var req_data = {
      page: this.data.now_page + 1,
      limit: 9999,
      quick_search: this.data.detail.template_no
    };
    // 发起请求
    var result = app.request_api('admin/TotalBom/index?order=total_bom_id,desc', req_data, false);
    result.then(res => {
      console.log(res)
      if (is_search == 1) {
        this.setData({
          list_data: [],
          now_page: 0,
          list_total: 0,
        })
      }
      this.setData({
        list_data: this.data.list_data.concat(res.list),
        list_total: res.total,
        now_page: this.data.now_page + 1,
      });
    })
  },

  // 预览图片
  PreviewImg: function (events) {
    var pic_arr = events.currentTarget.dataset.pic;
    if (pic_arr.length == 0) {
      return false;
    }
    // 调用
    wx.previewImage({
      current: pic_arr[0],
      urls: pic_arr
    })
  },

  // 展示更多
  showMore: function (events) {

    var index = events.currentTarget.dataset.index;

    var content = this.data.detail.bom_list[index].bom_name;
    wx.showToast({
      title: content,
      icon: 'none',
      duration: 3000,
    });
  },

  // 编辑样板
  template_update: function (events) {
    var __this = this;
    // 跳转
    wx.navigateTo({

      url: '/alpha/pages/alpha_template_add/index?productId=' + __this.data.detail.id,
      events: {
        // 当修改完成时
        changeData: function (data) {
          // 重新请求数据
          __this.get_template_detail();
        }
      }
    });
  },

  // 关闭生产
  template_close: function (events) {
    var __this = this;
    // 确认提示
    wx.showModal({
      title: '提示',
      content: '您确定要关闭生产吗',
      success(res) {
        if (res.confirm) {
          __this.template_close_request();
        }
      },
    });
  },

  // 关闭生产请求
  template_close_request: function (index) {
    var __this = this;
    var template_id = __this.data.detail.template_id;
    var result = app.request_api('admin/template/closeTemplate', {
      id: template_id
    }, true);
    result.then(res => {
      wx.showToast({
        title: '已关闭生产',
        icon: 'none',
        duration: 2000,
      });
      __this.data.detail.status = 99;
      __this.setData({
        detail: __this.data.detail
      });
      // 向上一级页面传递参数
      var eventChannel = __this.getOpenerEventChannel();
      eventChannel.emit('changeCloseData', {});
    });
  },

  // 确认生产
  template_product: function (events) {
    var __this = this;
    // 确认提示
    wx.showModal({
      title: '提示',
      content: '您确定要开始生产吗',
      success(res) {
        if (res.confirm) {
          __this.template_product_request();
        }
      },
    });
  },

  // 确认生产请求
  template_product_request: function (index) {
    var __this = this;
    var template_id = __this.data.detail.template_id;
    var result = app.request_api('admin/template/postConfirmProduct', {
      template_id: template_id
    }, true);
    result.then(res => {
      wx.showToast({
        title: '已开始生产',
        icon: 'none',
        duration: 2000,
      });
      // 修改状态
      __this.data.detail.status = 3;
      __this.setData({
        detail: __this.data.detail
      });
      // 向上一级页面传递参数
      var eventChannel = __this.getOpenerEventChannel();
      eventChannel.emit('changeProductData', {});
    });
  },

  // 切换选项卡
  ChangeNav: function (events) {
    var id = events.currentTarget.dataset.id;
    console.log("id", id)
    this.setData({
      nav_active_id: id
    });
  },

  // 预览图片
  PreviewImage: function (events) {
    var src = events.currentTarget.dataset.src;
    // 调用
    wx.previewImage({
      current: src,
      urls: [src]
    })
  },

  // 跳转到详情页
  GoDetail: function (events) {
    var __this = this;
    var total_bom_id = events.currentTarget.dataset.id;
    var template_no = events.currentTarget.dataset.no;
    // 打开详情页面
    wx.navigateTo({
      url: '/pages/wuliao_follow_detail/wuliao_follow_detail?total_bom_id=' + total_bom_id + '&template_no=' + template_no,
    });
  },

  // 采购时间
  bindDateChange: function (e) {
    let index = e.currentTarget.dataset.index
    var bianl = `batch_form.skus[${index}].expectReturnDate`;
    this.setData({
      [bianl]: e.detail.value
    })
  },
  // 采购时间
  colorChange: function (e) {
    let index = e.currentTarget.dataset.index
    var bianl = `batch_form.skc`;
    this.setData({
      [bianl]: e.detail.value
    })
  },
  // 采购时间
  bindDateChange2: function (e) {
    let index = e.currentTarget.dataset.index
    var bianl = `batch_form2.skus[${index}].expectReturnDate`;
    this.setData({
      [bianl]: e.detail.value
    })
  },

  purchase_detail: function (e) {
    console.log("purchase_detail")
  },
  noop: function (e) {
    console.log("noop")
  },



  // 新增供应商
  add_supply: function (e) {
    const __this = this;
    // 跳转到添加供应商界面
    wx.navigateTo({
      url: '/pages/supply_add/supply_add',
      events: {
        // 当添加完成时
        changeData: function (data) {
          // 重新加载数据
          __this.setData({
            factory_keywords: data.simple_name,
            factory_list: [],
            factory_page: 0,
            factory_total: 0
          });
          __this.get_factory_list(1);
        }
      }
    });
  },
  handleBindingMaterial(event) {
    // const item = event.currentTarget.dataset.item
    // const orderCode = event.currentTarget.dataset.ordercode
    // const obj = {
    //   orderCode: orderCode,
    //   materialItem: item.materialItem,
    //   bomOrderCode: item.bomOrderCode,
    //   skuCode: item.skuCode
    // }
    this.setData({
      showMaterialInquiry: true
    })
  },
  // 绑定物料
  async handleSelect(event){
    const row = event.detail.row
    const params = {
      ...this.data.rowData,
      materialSupplierSkuId: row.supplierSkuCode,
      materialCode: row.materialCode,
      materialName: row.materialName
    }
    this.setData({
      rowData: params
    })
  
    
  },
  // 物料删除行
  async handleDelete(event) {
    try {
      const item = event.currentTarget.dataset.item
      const params = {
        materialItem: item.materialItem,
        bomOrderCode: item.bomOrderCode
      }
      const res = await common.request_api(
        "/api/pdm/sgsPdmPlateTask/delBomItem",
        params,
        true,
        "post"
      )
      if(res.code === 200) {
        wx.showToast({
          title: '删除成功!',
          icon: 'success',
        })
        this.get_plate_tasts(this.data.detail.productNo)
      }
    } catch {
      
    }
  },
  // 新增采购单
  handleAddPurchaseOrder() {
    wx.navigateTo({
      url: '/alpha/pages/alpha_add_purchase_order/index',
    });
  },
  handlePickerChange(e) {
    const formName = e.target.dataset.formname
    const isValue = e.target.dataset.value
    const isValueName = e.target.dataset.valuename
    const listName = e.target.dataset.listname
    const formData = this.data[formName]
    let data = this.data[listName][e.detail.value]
    formData[isValue] = data.value
    formData[isValueName] = data.label
    this.setData({
      rowData: formData
    })
  },
  // 编辑版单
  handleEditVersionSheet(event) {
    console.log(event);
    const item = event.currentTarget.dataset.item
    const orderCode = event.currentTarget.dataset.ordercode
    item.orderCode = orderCode
    item.materialSupplierSkuId = item.skuId
    this.setData({
      showVersionSheet: true,
      rowData: item
    })
  },
  // 编辑版单确认
  async versionSheetConfirm(event) {
    console.log(event.detail);
    const item = this.data.rowData
    console.log('itemitemitemitemitem',item)
    const params = {
      materialSupplierSkuId: item.materialSupplierSkuId,
      orderCode: item.orderCode,
      bomOrderCode: item.bomOrderCode,
      materialItem: item.materialItem,
      outsourceType: item.outsourceType
    }
    try {
      const res = await common.request_api(
        "/api/pdm/sgsPdmPlateTask/bindMaterialSku",
        params,
        true,
        "post"
      )
      if(res.code === 200) {
        this.setData({
          rowData:{}
        })
      this.setData({ showVersionSheet: false, rowData: {} });
        wx.showToast({
          title: '编辑成功！',
          icon: 'success',
        })
        this.get_plate_tasts(this.data.detail.productNo)
      }
    } catch {

    }
  },

  onClose() {
    this.setData({ showVersionSheet: false, rowData: {} });
  },
})
